package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.Orders;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author 衷岚
 * @version 1.0
 */
@RestController("UserOrderController")
@RequestMapping("/user/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/submit")
    @ApiOperation("提交订单")
    public Result add(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        OrderSubmitVO orderSubmitVO = orderService.add(ordersSubmitDTO);

        return Result.success(orderSubmitVO);
    }

    @PutMapping("/payment")
    @ApiOperation("支付")
    public Result payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) {
        log.info("订单支付：{}",ordersPaymentDTO);

        /**
         * 异步更新
         * try-catch包裹保证消息转发失败不影响支付操作，不会回滚。
         *         订单状态为已支付
         *         推送订单给商家
         */

        try {
            rabbitTemplate.convertAndSend("pay.topic","pay.success",ordersPaymentDTO);
            log.info("success...");
        } catch (AmqpException e) {
            log.error("支付成功，但通知交易服务失败...",e);
        }

        //paySuccess(ordersPaymentDTO);

        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        log.info("生成支付交易单...");
        return Result.success(orderPaymentVO);

    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "takeout.order.pay.queue",durable = "true"),
            exchange = @Exchange(name = "pay.topic",type = ExchangeTypes.TOPIC),
            key = "pay.success"
    ))
    private void paySuccess(OrdersPaymentDTO ordersPaymentDTO){
        log.info("支付成功");
        //更新订单状态
        orderService.update(ordersPaymentDTO);

        Orders order = orderService.getByNumber(ordersPaymentDTO.getOrderNumber());



        //通过websocket向商家客户端推送信息
        //type orderId content
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 1);//1表示来单提醒， 2表示客户催单
        map.put("orderId",order.getId());
        map.put("content","订单号："+ordersPaymentDTO.getOrderNumber());
        //转为jason字符串
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);

    }


    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @GetMapping("/historyOrders")
    @ApiOperation("历史订单查询")
    public Result<PageResult> page(int page, int pageSize, Integer status) {
        PageResult pageResult = orderService.pageQuery4User(page, pageSize, status);
        return Result.success(pageResult);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/orderDetail/{id}")
    @ApiOperation("查询订单详情")
    public Result<OrderVO> details(@PathVariable("id") Long id) {
        OrderVO orderVO = orderService.details(id);
        return Result.success(orderVO);
    }

    @GetMapping("reminder/{id}")
    @ApiOperation("用户催单")
    public Result reminder(@PathVariable("id") Long id) {
        orderService.reminder(id);

        return Result.success();
    }

    @PutMapping("cancel/{id}")
    @ApiOperation("取消订单")
    public Result cancel(@PathVariable("id") Long id) {
        log.info("取消订单,订单id:{}",id);
        OrdersCancelDTO ordersCancelDTO = new OrdersCancelDTO();
        ordersCancelDTO.setId(id);
        ordersCancelDTO.setCancelReason("用户自动取消");
        orderService.cancel(ordersCancelDTO);
        return Result.success();
    }

    @PostMapping("repetition/{id}")
    @ApiOperation("再来一单")
    public Result repetition(@PathVariable("id") Long id) {
        log.info("再来一单，之前订单id:{}",id);
        orderService.repetition(id);
        return Result.success();
    }



}
